//
//  AccountRegisterViewController.m
//  Finance
//
//  Created by Hu Jianguo on 13-4-16.
//  Copyright (c) 2013年 cheng xiang. All rights reserved.
//

#import "AccountRegisterViewController.h"
//#import "ASIFormDataRequest.h"
#import <QuartzCore/QuartzCore.h>
#import "AnalysisJson.h"
#import "MultiThreading.h"
#import "AccountLoginViewController.h"
#import "GetRegisterCodeViewController.h"
@interface AccountRegisterViewController ()

@end

@implementation AccountRegisterViewController
@synthesize txtUserEmail;
@synthesize txtUserName,txtUserPassword;
@synthesize txtRegisterCode;
@synthesize btnRegister,btnGetReigisterCode,txtUserPasswordConfirm;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidAppear:(BOOL)animated
{
    AppDelegate* mydelegate =(AppDelegate *)[[UIApplication sharedApplication] delegate];
    if(mydelegate.registercode != nil)
    {
        self.txtRegisterCode.text = mydelegate.registercode;
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.txtUserName.tag = 2;
    self.txtUserPassword.tag = 3;
    self.txtUserEmail.tag = 4;
    self.txtRegisterCode.tag = 5;
    
        
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStyleBordered target:self action:@selector(back)];
    [leftItem setBackgroundImage:[UIImage imageNamed:@"btn.png"] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    [leftItem setBackgroundImage:[UIImage imageNamed:@"btn.png"] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    
    [self.navigationItem setLeftBarButtonItem:leftItem];
    
    self.txtUserName.delegate = self;
    self.txtUserPassword.delegate = self;
    self.txtUserEmail.delegate = self;
    self.txtRegisterCode.delegate = self;
    
    UIColor* bk = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"beij.png"]];
    
    [self.view setBackgroundColor:bk];
}

-(void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma -
-(void)doBack:(id)sender
{
    CATransition *transion = [CATransition animation];
    transion.duration = 0.3;
    transion.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    transion.type = kCATransitionFade;
    [self.view.layer addAnimation:transion forKey:nil];
    [self.view removeFromSuperview];
}

#pragma - textdelegate
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    NSInteger textID = textField.tag;
//    if (textID == 1)
//    {
//        self.phoneNumber.text =@"";
//        
//    }
    
    if(textID == 2)
    {
         self.txtUserName.text = @"";
        [self changeTxtFieldPosition:5 TextFieldFrame:textField.frame];
    }

    if(textID == 3)
    {
        self.txtUserPassword.text = @"";
        [self changeTxtFieldPosition:10  TextFieldFrame:textField.frame];
    }
    
    if(textID == 4)
    {
        self.txtUserEmail.text = @"";
        [self changeTxtFieldPosition:15  TextFieldFrame:textField.frame];
    }
    
    if(textID == 4 || textID == 5)
    {
        [self changeTxtFieldPosition:30  TextFieldFrame:textField.frame];
    }
    
}

-(void)changeTxtFieldPosition:(NSInteger)pos TextFieldFrame:(CGRect)frame
{
    //CGRect frame = textField.frame;
    int offset = frame.origin.y + pos - (self.view.frame.size.height - 216.0);//键盘高度216
    
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    
    //将视图的Y坐标向上移动offset个单位，以使下面腾出地方用于软键盘的显示
    if(offset > 0)
        self.view.frame = CGRectMake(0.0f, -offset, self.view.frame.size.width, self.view.frame.size.height);
    
    [UIView commitAnimations];
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    NSInteger textID = textField.tag;
    if (textID == 1 || textID == 2|| textID == 3 || textID == 4 || textID == 5)
    {
        [self.txtUserName resignFirstResponder];
        self.view.frame =CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    }
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if([self.txtUserName isFirstResponder])
    {
        [self.txtUserPassword becomeFirstResponder];
    }
    else if([self.txtUserPassword isFirstResponder])
    {
        [self.txtUserEmail becomeFirstResponder];
    }
    else if([self.txtUserPasswordConfirm isFirstResponder])
    {
        [self.txtUserEmail becomeFirstResponder];
    }
    else if([self.txtUserEmail isFirstResponder])
    {
        //[self.txtUserEmail resignFirstResponder];
        [self.txtRegisterCode becomeFirstResponder];
    }
    else if([self.txtRegisterCode isFirstResponder])
    {
        [self.txtRegisterCode resignFirstResponder];
    }
    
    return  YES;
}

#pragma - 用户注册
-(IBAction)userRegister:(id)sender
{
    //隐藏键盘
    [self.txtUserName resignFirstResponder];
        
    if(self.txtUserName.text == nil)
    {
        [self showMessageBox:@"提示" content:@"用户名不能空."];
        return;
    }

    if(self.txtUserPassword.text == nil || self.txtUserPasswordConfirm.text == nil)
    {
        [self showMessageBox:@"提示" content:@"用户的密码不能空."];
        return;
    }

    NSString* password = self.txtUserPassword.text;
    NSString* password2 = self.txtUserPasswordConfirm.text;
    if([password compare:password2] != NSOrderedSame)
    {
        [self showMessageBox:@"提示" content:@"密码不一致."];
        return;
    }
    
    NSString* strEmail = self.txtUserEmail.text;
    if(strEmail != nil)
    {
        if([strEmail rangeOfString:@"@"].location == NSNotFound)
        {
            [self showMessageBox:@"提示" content:@"邮件格式不正确."];
            return;
        }
    }

    if(self.txtRegisterCode.text == nil)
    {
        [self showMessageBox:@"提示" content:@"验证码不能为空."];
        return;
    }

    //组请求报文
    NSDictionary *header = [AnalysisJson PackageJsonHeader:@"W105"];
    NSDictionary *body = [self setRegisterBody:self.txtUserName.text UserPassword:self.txtUserPassword.text UserEmail:self.txtUserEmail.text CheckCode:self.txtRegisterCode.text];

    NSData *requestJson = [AnalysisJson PackageJsonFromHeader:header andBody:body];
    NSString *jsonString = [[NSString alloc] initWithData:requestJson encoding:NSUTF8StringEncoding];

    NSLog(@"%@",jsonString);

    //发送报文
    [self sendRegister: requestJson];

}

-(NSDictionary*)setRegisterBody:(NSString*)userName UserPassword:(NSString*)userPassword
UserEmail:(NSString*)userEmail  CheckCode:(NSString*)checkCode
{
    NSMutableDictionary * dict = [[NSMutableDictionary alloc] init];
    [dict setObject:userName forKey:@"userName"];
    [dict setObject:userPassword forKey:@"password"];
    [dict setObject:userEmail forKey:@"email"];
    [dict setObject:checkCode forKey:@"validCode"];
    
    return  dict;
}

-(void)sendRegister:(NSData*)jsonData
{
    [MultiThreading getDataFromNetwork:[SERVICE_URL stringByAppendingString:@"RegisterUser"] toObject:self callBack:@selector(requestUserRegisterCallBack:) withBody:jsonData];
}

-(void)requestUserRegisterCallBack:(NSDictionary *)dic
{
    if(dic == nil)
    {
        return;
    }
    
    NSDictionary* header = dic[@"header"];
    //NSLog(@"%d",[header isEqual:[NSNull null]]);
    if(header != nil && [header isEqual:[NSNull null]] !=1 && header.count != 0)
    {
        if([header[@"returnCode"] isEqualToString:@"000"] == 0)
        {
             [self showLogin:self.txtUserName.text];
        }
        else
        {
            [self showMessageBox:@"注册提示" content:header[@"returnMessage"]];
        }
       
        return;
    }
}

-(IBAction)getRegisterCode:(id)sender
{
    GetRegisterCodeViewController* registercode = [[GetRegisterCodeViewController alloc] initWithNibName:@"GetRegisterCodeViewController" bundle:nil];
    [self.navigationController pushViewController:registercode animated:YES];
}

-(void)showLogin:(NSString*)userName
{
    CGSize winsize = self.view.frame.size;
    AccountLoginViewController* accountLogin = [[AccountLoginViewController alloc] initWithNibName:@"AccountLoginViewController" bundle:nil];
    accountLogin.registerUserName = userName;
    
    accountLogin.view.frame = CGRectMake(0, -2,winsize.width,winsize.height);
    [self.navigationController pushViewController:accountLogin animated:YES];
}

#pragma -
-(void)showMessageBox:(NSString*)title content:(NSString*)content
{
    UIAlertView* msg = [[UIAlertView alloc] initWithTitle:title message:content delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    [msg show];
}
@end
